package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollUtil;
import com.itheima.domain.mongo.*;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementServiceImpl implements MovementService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RedisIdService redisIdService;

    @Override
    public void save(Movement movement) {
        //1.往动态详情表中插入一条
        //1.1 保存之前设置一个pid(推荐系统用)
        movement.setPid(redisIdService.getNextId(ConstantUtil.MOVEMENT_ID));

        mongoTemplate.save(movement);

        //2.往个人动态详情表中插入一条
        //2.1 获取当前用户id
        Long userId = movement.getUserId();

        //2.2 封装个人动态详情
        MyMovement myMovement = new MyMovement();
        myMovement.setPublishId(movement.getId());
        myMovement.setCreated(movement.getCreated());

        //2.3 插入数据
        mongoTemplate.save(myMovement,ConstantUtil.MOVEMENT_MINE+userId);

        //3.查询好友列表
        //3.1 创建条件查询对象
        Query query = new Query(Criteria.where("userId").is(userId));

        //3.2 查询friend表获取好友列表
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        //4.往每个好友的好友动态表中插入一条
        if (CollUtil.isNotEmpty(friends)) {
            friends.forEach(f->{
                //4.1获取每个好友id
                Long friendId = f.getFriendId();

                //4.2封装好友动态
                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setUserId(userId);
                friendMovement.setPublishId(movement.getId());
                friendMovement.setCreated(movement.getCreated());

                //4.3往好友动态表中插入数据
                mongoTemplate.save(friendMovement,ConstantUtil.MOVEMENT_FRIEND+friendId);
            });
        }
    }

    @Override
    public PageBeanVo findMyMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.创建条件对象
        Query query = new Query();
        //2.查询总条数(个人动态表)
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_MINE + userId);

        //3.给条件对象添加分页参数和排序
        query.skip((pageNum-1)*pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4.查询当前页数据
        //4.1 查询个人动态表(里面只有动态id)
        List<MyMovement> myMovements = mongoTemplate.find(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);

        //4.2 遍历list,获取每个动态id,查询动态详情表,获取movement,将每个movement放入集合中
        List<Movement> movements = new ArrayList<>();

        if (CollUtil.isNotEmpty(myMovements)) {
            myMovements.forEach(myMovement -> {
                //查询动态详情表,获取movement
                Movement movement = mongoTemplate.findById(myMovement.getPublishId(), Movement.class);

                //将每个movement放入集合中
                movements.add(movement);
            });
        }
        //5.封装vo返回
        return new PageBeanVo(pageNum,pageSize,count,movements);
    }

    @Override
    public PageBeanVo findFriendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.创建条件对象
        Query query = new Query();

        //2.查询我的好友动态表获取总数量
        long count = mongoTemplate.count(query, ConstantUtil.MOVEMENT_FRIEND + userId);

        //3.给条件对象添加分页参数和排序
        query.skip((pageNum-1)*pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4.查询我的好友动态表获取当前页数据(只有发布用户id和动态id)
        List<FriendMovement> friendMovements = mongoTemplate.find(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);

        //5.遍历动态集合,获取动态id,查询动态详情,将每个详情放入list中
        List<Movement> movementList = new ArrayList<>();
        if (CollUtil.isNotEmpty(friendMovements)) {
            friendMovements.forEach(fm->{
                //获取动态id,查询动态详情,
                Movement movement = mongoTemplate.findById(fm.getPublishId(), Movement.class);

                //将每个详情放入list中
                movementList.add(movement);
            });
        }

        //6.封装pageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,movementList);
    }

    @Override
    public PageBeanVo findRecommendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.创建条件对象(推荐给我的)
        Query query = new Query(Criteria.where("userId").is(userId));

        //2.查询推荐动态表获取总数量
        long count = mongoTemplate.count(query, RecommendMovement.class);

        //3.给条件对象添加分页和排序参数
        query.skip((pageNum-1)*pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4.查询推荐动态表获取推荐动态集合
        List<RecommendMovement> recommendMovements = mongoTemplate.find(query, RecommendMovement.class);

        //5.遍历推荐动态集合,获取动态id,查询动态详情,将每个详情放入动态list中
        List<Movement> movements = new ArrayList<>();
        if (CollUtil.isNotEmpty(recommendMovements)) {
            recommendMovements.forEach(rm->{
                //获取动态id,查询动态详情,将每个详情放入动态list中
                Movement movement = mongoTemplate.findById(rm.getPublishId(), Movement.class);
                movements.add(movement);
            });
        }
        //6.封装pageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,movements);
    }

    @Override
    public Movement findById(ObjectId id) {
        return mongoTemplate.findById(id,Movement.class);
    }

    @Override
    public PageBeanVo findByCondition4Page(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        //1.创建条件对象
        Query query = new Query();
        //1.1若userId不为空添加userId的条件
        if (userId!=null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        //1.2若state不为空添加state的条件
        if (state!=null) {
            query.addCriteria(Criteria.where("state").is(state));
        }

        //2.查询总条数(查询动态表)
        long count = mongoTemplate.count(query, Movement.class);

        //3.追加条件(分页和排序)
        query.skip((pageNum-1)*pageSize).limit(pageSize)
                .with(Sort.by(Sort.Order.desc("created")));

        //4.查询动态表获取当前页数据
        List<Movement> movements = mongoTemplate.find(query, Movement.class);

        //5.封装pageBeanVo且返回
        return new PageBeanVo(pageNum,pageSize,count,movements);
    }

    @Override
    public void update(Movement movement) {
        mongoTemplate.save(movement);
    }
}
